package com.jfl.core.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import lombok.extern.slf4j.Slf4j;

/**
 * jwt过滤
 * 
 * @author 赵炎
 * @version [V1.00, 2019年7月17日]
 * @see [相关类/方法]
 * @since V1.00
 */
@Slf4j
public class
JwtFilter extends BasicHttpAuthenticationFilter
{
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response)
    {
        if(isLoginAttempt(request, response))
        {
            try
            {
                executeLogin(request, response);
            }
            catch (Exception e)
            {
                log.error("尝试登录异常", e);
            }
        }
        return true;
    }
    
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response)
        throws Exception
    {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时发送一个option请求
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name()))
        {
            return false;
        }
        return super.preHandle(request, response);
    }
}
